<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="filter-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="queryParams.roleName"
            placeholder="请输入角色名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input
            v-model="queryParams.roleCode"
            placeholder="请输入角色编码"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
    </el-row>

    <!-- 角色列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="roleList"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="roleName" label="角色名称" :show-overflow-tooltip="true" />
        <el-table-column prop="roleCode" label="角色编码" :show-overflow-tooltip="true" />
        <el-table-column prop="description" label="角色描述" :show-overflow-tooltip="true" />
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template slot-scope="scope">
            {{ scope.row.createTime ? scope.row.createTime.split('T')[0] + ' ' + scope.row.createTime.split('T')[1].split('.')[0] : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isDeleted === 0 ? 'success' : 'danger'">
              {{ scope.row.isDeleted === 0 ? '正常' : '已禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-key"
              @click="handlePermission(scope.row)"
            >分配权限</el-button>
            <el-button
              v-if="scope.row.isDeleted === 0"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >禁用</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="form.roleCode" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            type="textarea"
            v-model="form.description"
            placeholder="请输入角色描述"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="permissionOpen" width="500px" append-to-body>
      <el-tree
        ref="permissionTree"
        :data="permissionOptions"
        :props="{ label: 'permissionName', children: 'children' }"
        show-checkbox
        node-key="id"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPermission">确 定</el-button>
        <el-button @click="permissionOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'Role',
  data() {
    return {
      // 罩层
      loading: false,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示权限弹出层
      permissionOpen: false,
      // 查询参数
      queryParams: {
        roleName: undefined,
        roleCode: undefined
      },
      // 表单参数
      form: {
        id: undefined,
        roleName: undefined,
        roleCode: undefined,
        description: undefined
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: '角色名称不能���空', trigger: 'blur' }
        ],
        roleCode: [
          { required: true, message: '角色编码不能为空', trigger: 'blur' }
        ]
      },
      // 角色列表数据
      roleList: [],
      // 权限树选项
      permissionOptions: [],
      // 当前选中的角色ID
      currentRoleId: undefined
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询角色列表 */
    async getList() {
      this.loading = true
      try {
        const res = await request({
          url: '/api/admin/roles',
          method: 'get',
          params: this.queryParams
        })
        if (res.code === 200) {
          this.roleList = res.data
        }
      } catch (error) {
        if (error !== '登录已过期') {
          this.$message.error('获取角色列表失败')
        }
      }
      this.loading = false
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        roleName: undefined,
        roleCode: undefined
      }
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加角色'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.form = { ...row }
      this.open = true
      this.title = '修改角色'
    },
    /** 分配权限按钮操作 */
    async handlePermission(row) {
      this.currentRoleId = row.id
      try {
        // 获取系统所有权限数据
        const [allPermRes, rolePermRes] = await Promise.all([
          request({
            url: '/api/admin/permissions',
            method: 'get'
          }),
          request({
            url: `/api/admin/findPersission/${row.id}`,
            method: 'get'
          })
        ])

        if (allPermRes.code === 200) {
          // 构建权限树
          this.permissionOptions = this.handleTree(allPermRes.data)
          
          // 获取角色权限，设置已选中的权限
          if (rolePermRes.code === 200) {
            this.$nextTick(() => {
              // 从角色权限中提取权限ID
              const rolePermIds = rolePermRes.data.map(item => item.id)
              // 设置树形件的选中状态
              this.$refs.permissionTree.setCheckedKeys(rolePermIds)
            })
          }
          this.permissionOpen = true
        }
      } catch (error) {
        if (error !== '登录已过期') {
          this.$message.error('获取权限数据失败')
        }
      }
    },
    /** 提交权限 */
    async submitPermission() {
      try {
        // 获取选中的权限ID（包括父节点）
        const checkedKeys = this.$refs.permissionTree.getCheckedKeys()
        // 获取半选中的父节点ID
        const halfCheckedKeys = this.$refs.permissionTree.getHalfCheckedKeys()
        // 合并所有权限ID并去重
        const permissionIds = [...new Set([...checkedKeys, ...halfCheckedKeys])]
        
        // 提交更新后的权限
        const res = await request({
          url: `/api/admin/roles/${this.currentRoleId}/permissions`,
          method: 'put',
          data: permissionIds
        })
        
        if (res.code === 200) {
          this.$message.success('分配权限成功')
          this.permissionOpen = false
        }
      } catch (error) {
        if (error !== '登录已过期') {
          this.$message.error('分配权限失败')
        }
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认禁用名称为"' + row.roleName + '"的角色?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await request({
            url: `/api/admin/roles/${row.id}/status`,
            method: 'put'
          })
          if (res.code === 200) {
            this.$message.success('禁用成功')
            this.getList()
          }
        } catch (error) {
          if (error !== '登录已过期') {
            this.$message.error('禁用失败')
          }
        }
      })
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        roleName: undefined,
        roleCode: undefined,
        description: undefined
      }
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            if (this.form.id) {
              // 修改
              await request({
                url: `/api/admin/roles/${this.form.id}`, // 修改为带ID的URL
                method: 'put',
                data: this.form
              })
            } else {
              // 新增
              await request({
                url: '/api/admin/roles',
                method: 'post',
                data: this.form
              })
            }
            this.$message.success('操作成功')
            this.open = false
            this.getList()
          } catch (error) {
            if (error !== '登录已过期') {
              this.$message.error('操作失败')
            }
          }
        }
      })
    },
    /** 转换树形数据结构 */
    handleTree(data) {
      const parents = data.filter(item => item.parentId === 0)
      const children = data.filter(item => item.parentId !== 0)
      
      const translator = (parents, children) => {
        parents.forEach(parent => {
          children.forEach((child, index) => {
            if (child.parentId === parent.id) {
              const temp = JSON.parse(JSON.stringify(children))
              temp.splice(index, 1)
              translator([child], temp)
              if (parent.children) {
                parent.children.push(child)
              } else {
                parent.children = [child]
              }
            }
          })
        })
      }
      
      translator(parents, children)
      return parents
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.filter-card {
  margin-bottom: 10px;
}
.table-card {
  margin-bottom: 20px;
}
.mb8 {
  margin-bottom: 8px;
}
.small-padding {
  padding-left: 5px;
  padding-right: 5px;
}
.fixed-width {
  min-width: 200px;
}
</style> 